<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>结算页</title>
</head>
<body>
    <h1>结算页</h1>
    <div>
        <p id="name"></p>
        <p id="limit"></p>
        <p>价格：<span id="price"></span></p>

    </div>
    <div>
        <label>购买数量：<input type="text" name="buyNum" id="buyNum" value="2"></label>
        <label>收货地址：<input type="text" name="address" id="address" value="北京市朝阳区"></label>
        <button onclick="submitOrder()">提交订单</button>
        <input type="hidden" name="limitNum" id="limitNum" value="0">
    </div>
    <div>
    </div>

<script th:src="@{/js/jquery-3.6.0.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/common.js}"></script>
<script>
    $(document).ready(init);

    let token = "";
    let timestamp = "";

    function init() {
        activityQuery(getParameterByName("code"));
        tokenQuery();
    }

    function activityQuery(code) {
        const url = API["activityData"];
        const params = {code: code};
        get(url, params, function(result) {
            if (result.code == RESULT_OK) {
                const data = result.data;
                $("#name").text(data.name);
                $("#price").text((data.price/100).toFixed(2));
                if (data.limit > 0) {
                    $("#limit").text("本次限购" + data.limit + "件！");
                    $("input[name='limitNum']").val(data.limit);
                }
            }
        })
    }

    function tokenQuery() {
        const url = API["settlementToken"];
        const params = {
            token: getParameterByName("token"),
            timestamp: getParameterByName("timestamp"),
        };
        get(url, params, function(result){
            token = result["token"];
            timestamp = result["timestamp"];
        })
    }

    function submitOrder() {
        const code = getParameterByName("code");
        const buyNum = $("#buyNum").val();
        const address = $("#address").val();
        const limitNum = $("#limitNum").val();

        if (buyNum > limitNum) {
            alert("只能购买 " + limitNum + " 件商品");
            return
        }

        const url = getUrl(API["submitOrder"], {token: token, timestamp: timestamp});
        const params = {code: code, buyNum: buyNum, address: address};
        post(url, params, function(result) {
            if (result.code == RESULT_OK) {
                redirect(PAGE["pay"]);
            } else if (result.code == TOKEN_EXPIRE) {
                alert("令牌失效")
            } else {
                redirect(PAGE["fail"]);
            }
        })
    }
</script>
</body>
</html>